package com.zhulanhua.blogs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhulanhua.blogs.Utils.Code;
import com.zhulanhua.blogs.Utils.RequestContextUtils;
import com.zhulanhua.blogs.Utils.TokenUtils;
import com.zhulanhua.blogs.dao.UserDao;
import com.zhulanhua.blogs.domain.User;
import com.zhulanhua.blogs.exception.BusinessException;
import com.zhulanhua.blogs.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    TokenUtils tokenUtils;

    @Autowired
    UserDao userDao;

    @Override
    public Object LoginToken(HttpRequest httpRequest) {
        return null;
    }

    @Override
    public String Login(User user) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().eq(User::getUserName, user.getUserName())
                .eq(User::getPassword, user.getPassword());
        User user1 = userDao.selectOne(qw);
        if (user1 == null){
            throw new BusinessException(Code.BUSINESS_ERR,"用户名或密码错误");
        }

        long time = System.currentTimeMillis();

        user1.setLoginTime(new Date(time));
        String token = tokenUtils.getToken(user1.getUserId() + "", user1.getUserRole(), time);
        userDao.updateById(user1);
        return token;
    }

    @Override
    public boolean isLoginTime(Date date) {
        User user = RequestContextUtils.getUser();
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUserId, user.getUserId()).eq(User::getLoginTime, user.getLoginTime());
        User user1 = userDao.selectOne(qw);
        if (user == null){
            return true;
        }
        return false;
    }
}
